<!--
 * @Author: 梁卓
 * @Date: 2022-02-01 20:37:42
 * @LastEditTime: 2022-02-13 12:16:08
 * @LastEditors: Please set LastEditors
 * @Description: 角色管理界面
 * @FilePath: \dreamUi\src\views\system\role.vue
-->
<template>
  <div>
    <el-card>
        <el-row>
          <el-col :span="8">
            <el-input  v-model="queryInfo.queryString" clearable placeholder="Please input" @clear="findPage">
              <el-button icon="el-icon-search" slot="append" @click="findPage"></el-button>
            </el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="insert" v-hasPermission="['PRE_ROLE_INSERT']">添加角色</el-button>
          </el-col>
      </el-row>
      <el-table  v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号"  />
        <el-table-column prop="label" label="角色标签" />
        <el-table-column prop="code" label="角色标签值" />
        <el-table-column  fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" circle size="small" v-hasPermission="['PRE_ROLE_UPDATE']" @click="updatePermission(scope)" />
            <el-button type="danger" icon="el-icon-delete" circle size="small" v-hasPermission="['PRE_ROLE_DELETE']"  @click="deletePermission(scope)"/>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="total > 0"
        :currentPage="queryInfo.currentPage"
        :page-sizes="[8,15,30,50]"
        :page-size= "queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total= total
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>
    <!-- 角色的添加和修改 -->
    <el-dialog :title="title" :visible.sync="open" width="35%" @closed="dialogClose">
      <el-form :model="form" ref="form" :rules="rule">
        <el-row>
          <el-col :span="11">
            <el-form-item label="角色标签" prop="label">
              <el-input v-model="form.label" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="角色标签值" prop="code">
              <el-input v-model="form.code"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-card>
              <div slot = "header" class = "clearfix">
                <span>选择对应的菜单</span>
              </div>
              <el-tree
              ref = "tree"
               :data = "menuList"
                show-checkbox
                :check-strictly="true"
                node-key="id"
                :props="defaultProps"
                @check-change="treeChange"
              />
            </el-card>
          </el-col>
        </el-row>
        <el-row :span="22">
          <el-col :span="22">
            <el-card class="Permission-class">
              <div slot = "header" class = "clearfix">
                <span>选择对应的权限</span>
              </div>
              <el-checkbox-group v-model="checkPermissions">
                <el-checkbox 
                  v-for="(item, index) in permissionList"
                  :label="item.label" 
                  size="small"
                  border
                  :key="index" 
                  @change="permissionChange(item)"/>
              </el-checkbox-group>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeFrom">取 消</el-button>
        <el-button type="primary" @click="insertPermission">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  name: 'DreamuiRole',

  data() {
    return {
      // 分页
      queryInfo: {
        pageNumber: 1,
        pageSize: 8,
        queryString: ''
      },
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      loading: true,
      // 添加或删除的标题
      title: '',
      // 是否打开对话框
      open: false,
      // 表单数据
      form: {},
      // 表单校验
      rule: {
        label: [
          {required: true, message: '请输入权限标签', trigger: 'blur'},
          {min: 1, max: 50, message: '权限标签的长度为1~50之间', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入权限标签值', trigger: 'blur'},
          {min: 1, max: 20, message: '权限标签的长度为1~20之间', trigger: 'blur'}
        ]
      },
      menuList: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      permissionList: [],
      checkPermissions: [],
      checkedPermissions: [],
      checkedMenus: []
    };
  },

  mounted() {
    
  },

  created() {
    this.findPage();
    this.findMenusAndPermission();
  },

  methods: {
    // 查询所有菜单信息
    findMenusAndPermission() {
      this.$ajax.get('/menu/findParent').then(res => {
        this.menuList = res.data.data
      });
      this.$ajax.get('/permission/findAll').then(res => {
        this.permissionList = res.data.data
      });
    },
    findPage() {
      this.$ajax.post('/role/findPage',this.queryInfo,).then(res => {
        this.tableData = res.data.rows;
        this.loading = false;
        this.total = res.data.total
      });
    },
    // 改变页码
    handleSizeChange(param) {
      this.queryInfo.pageSize = param;
      // 重新赋值
      this.findPage();
    },
    // 改变当前的页面
    handleCurrentChange(param) {
      this.queryInfo.pageNumber = param;
      this.findPage();
    },
    // 添加按钮事件
    insert(param) {
      this.title = '新增角色信息';
      this.open = true;
    },
    // 删除角色信息
    deletePermission(param) {
      this.$confirm(`您将永久删除-[${param.row.label}]-的角色, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$ajax.delete(`/role/delete/${param.row.id}`).then((res) => {
            this.$message.success(res.data.message);
            // 防止删除最后一页中最后一个数据时无法换页的问题
            this.queryInfo.pageNumber = 1;
            // 删除成功后更新数据
            this.findPage();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 关闭对话框事件
    dialogClose() {
      this.checkPermissions = []
      this.$refs.tree.setCheckedKeys([])
      this.checkedMenus = []
      // 将整个表单进行重置
      this.$refs.form.resetFields();
    },
    // 点击取消对话框
    closeFrom() { 
      this.checkedMenus = []
      this.checkPermissions = []
      this.$refs.tree.setCheckedKeys([])
      this.form = {}
      this.open = false
      this.findPage()
    },
    // 修改角色信息
    updatePermission(param) {
      this.form = param.row;
      this.checkedMenus = [];
      param.row.menus.forEach(item => {
        this.checkedMenus.push(item)
        if (item.children && item.children.length > 0) {
          item.children.forEach(childrens => {
            this.checkedMenus.push(childrens)
          });
        }
      });
      this.checkPermissions = []
      this.checkedPermissions = []
      param.row.permissions.forEach(item => {
        this.checkPermissions.push(item.label);
        this.checkedPermissions.push(item)
      });
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes(this.checkedMenus);
      });
      this.title = '修改角色信息';
      this.open = true;
    },
    // 添加角色
    insertPermission(param) {
      this.$refs.form.validate(val => {
        // 校验不同通过
        if (!val) {
          return this.$message.error('表单校验不通过，请检查后提交')
        }
        this.form.menus = this.checkedMenus
        this.form.permissions = this.checkedPermissions;
        // 判断是否时新增
        if (this.form.id === undefined || this.form.id === null) {
          this.$ajax.post('/role/insert',this.form).then(res => {
            this.$message.success(res.data.message);
            this.open = false;
            this.findPage();
          });
        } else {
          this.$ajax.put('/role/update',this.form).then(res => {
            this.$message.success(res.data.message);
            this.open = false;
            this.findPage();
          });
        }
      });
    },
    // 菜单树形空间选中后的回调
    treeChange() {
      this.checkedMenus = []
      // 获取选中值de数据
     const checks = this.$refs.tree.getCheckedNodes(false,true);
     checks.forEach(item => {
       this.checkedMenus.push(item);
     });
    },
    // 勾选权限的回调
    permissionChange(item) {
      this.checkedPermissions.push(item)
    }
  }
};
</script>

<style  scoped>
.Permission-class  {
  margin-top: 10px;
}
.el-checkbox {
  margin: 10px 10px;
}
</style>